﻿using Common.Net;
using KCPServer.Tools;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace KCPServer.Core.Net
{
    public partial class NServer : Singleton<NServer>
    {
        public Dictionary<int, ClientPeer> clientPeerDic = new Dictionary<int, ClientPeer>();
        public static event Action<MsgInfo> HandlerController;
        private TcpListener tcpListener;
        private int port = 6688;
        public Queue<MsgInfo> delayMsgInfo = new Queue<MsgInfo>();

        public void ShutDownById(int id)
        {
            throw new NotImplementedException();
        }

        public void Start()
        {
            StartTcpService();
            StartUdpService();
        }

        private void StartUdpService()
        {
            
        }

        private void StartTcpService()
        {
            try
            {
                tcpListener = new TcpListener(System.Net.IPAddress.Any, port); // Example port
                tcpListener.Start();
                Console.WriteLine($"TCP Server started on port {port}.");
                Task.Run(TcpListenForClients);
             
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                throw;
            }
        }

       async void TcpListenForClients()
        {
            try
            {
                while (true)
                {
                    TcpClient tcp = await tcpListener.AcceptTcpClientAsync();
                    ClientPeer clientPeer = new ClientPeer(tcp, this);
                    //生成一个唯一id
                    clientPeer.clientId = GetUniqueId();
                    clientPeerDic.Add(clientPeer.clientId, clientPeer);
                    Console.WriteLine("[客户端进来了]，分配id：" + clientPeer.clientId);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw;
            }
        }

        internal void DispatchMsgInfo()
        {
            if(delayMsgInfo.Count > 0)
            {
                lock (delayMsgInfo)
                {
                    while (delayMsgInfo.Count > 0)
                    {
                        var msgInfo = delayMsgInfo.Dequeue();
                        if (HandlerController != null)
                        {
                            HandlerController.Invoke(msgInfo);
                        }
                    }
                }
            }
        }

        private int GetNextClientId()
        {
            // Implement logic to get the next available client ID
            // This could be a simple incrementing counter or a more complex logic
            return clientPeerDic.Count + 1; // Example implementation
        }
        private int GetUniqueId()
        {
            var id=new Random().Next(0, 999999);
            while (clientPeerDic.ContainsKey(id))
            {
                id++;
            }
            return id;
        }
    }
}